package com.pl.lc.user.listener;

import cn.hutool.core.util.RandomUtil;
import com.pl.lc.common.config.RabbitKeyConfig;
import com.pl.lc.common.config.RedisKeyConfig;
import com.pl.lc.common.param.MqMsg;
import com.pl.lc.core.sms.AliSmsUtil;
import com.pl.lc.user.entity.SmsLog;
import com.pl.lc.user.mapper.SmsLogMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Author 小胤
 * @Date 2024/6/5 20:41
 * @注释
 *  * 发送注册短信业务
 *      * 1.生成随机证码
 *      *
 *      * 2.发送阿里云短信
 *      *
 *      * 3.存入redis中验证码
 *      *
 *      * 4.手机号验证码记录日志表
 */
@Component
public class SmsRabbitListener {
    /**
     * 队列的消费者
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SmsLogMapper smsLogMapper;
    @RabbitListener(queues = RabbitKeyConfig.Q_SENDSMS)
    public void smsListener(MqMsg msg){

        System.out.println("消费者得到消息  msg = " + msg);
    //    * 1.生成随机证码
        String code= RandomUtil.randomInt(1000,9999)+"";
    //    * 2.发送阿里云短信
        String phone = (String) msg.getMsg();
        System.out.println("phone = " + phone + "---验证码 = "+code);
        boolean result = AliSmsUtil.sendCode(phone, code);
        /**
         * 这里因为阿里云服务器发信息业务没开通 result替换为true 假设发送成功
         */
        if (true){
            switch (msg.getType()){
                // 1.注册验证码
                case 1:
                    //    * 3.存入redis中验证码
                    redisTemplate.opsForValue().set( RedisKeyConfig.SMS_RCODE+phone,code,RedisKeyConfig.SMS_RCODE_TIME,TimeUnit.SECONDS);
                    //* 4.手机号验证码记录日志表
                    smsLogMapper.insert(new SmsLog(phone,"注册验证码",code,new Date()));
                    break;
                //    登录验证码
                case 2:
                    redisTemplate.opsForValue().set(RedisKeyConfig.SMS_LCODE+phone,code,RedisKeyConfig.SMS_RCODE_TIME,TimeUnit.SECONDS);
                    smsLogMapper.insert(new SmsLog(phone,"登录验证码",code,new Date()));

                    break;
                //    密码找回验证码
                case 3:
                    break;
                default:
                    System.out.println("其他消息处理");
                    break;
            }
        }
    }
}